<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="司机所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="1.2">
        <el-input v-model.trim="query.param" style="width: 300px;" placeholder="请输入" clearable>
          <el-select slot="prepend" v-model="qtype" style="width: 140px;" placeholder="请选择">
            <el-option label="绑定司机编号" value="driverCode" />
            <el-option label="绑定司机姓名" value="driverName" />
          </el-select>
        </el-input>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[10020305,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <addQuotedPrice ref="addQuotedPrice" :parent-fetch-data="upDataTable" />
    <cartDriverDetail ref="cartDriverDetail" />
  </div>
</template>

<script>
  import {
    queryDriverPriceList,
    querySalesmanList
  } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import addQuotedPrice from './addQuotedPrice'
  import cartDriverDetail from './cartDriverDetail'
  export default {
    name: '',
    components: {
      addQuotedPrice,
      cartDriverDetail
    },
    props: {
      priceStatusMap: {
        type: Array,
        default() {
          return []
        }
      }
    },
    data() {
      return {
        treeData: [],
        qtype: null,
        query: {
          orgSNNo: null,
          param: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        visible: false,
        driverList: [],
        dataForm: {
          orgSNNo: '',
          driverCode: '',
          driverName: '',
          newDriverCode: ''
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '绑定司机编号',
            prop: 'driverCode',
            width: 110
          },
          {
            label: '绑定司机',
            prop: 'driverName'

          },
          {
            label: '司机所属机构',
            prop: 'orgName',
            showOverflowTooltip: true
          },
          {
            label: '用户数量',
            prop: 'csmTotalCount',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>{row.csmTotalCount}</el-link>
          )
          },
          {
            label: '居民用户',
            prop: 'csmCount1',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 1)}>{row.csmCount1}</el-link>
          )
          },
          {
            label: '非居民用户',
            prop: 'csmCount2',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 2)}>{row.csmCount2}</el-link>
          )
          },
          { label: '报价状态',
            prop: '',
            render: (h, { row }) => { return row.priceStatus ? <span>{ row.priceStatus && formatColumnMap(this.priceStatusMap, 'value', row.priceStatus, 'desc') }</span> : '' }
          },
          {
            label: '操作',
            className: 'action-col',
            width: 280,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                  v-permission={[10020305, 2]}
                    underline={false}
                    size='mini'
                    onClick={() => this.setPrice(row)}
                  >
                    设置报价
                  </el-link>
                  <el-link
                    v-show={row.priceStatus}
                   v-permission={[10020305, 3]}
                    underline={false}
                    size='mini'
                    onClick={() => this.detail(row)}
                  >
                    查看报价
                  </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      this.getTreeData()
    },
    beforeDestroy() {
    },
    methods: {

      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      // 切换司机选择所属机构
      async selectTreeChangeNew(value) {
        this.dataForm.orgId = value.orgId
        this.dataForm.orgName = value.orgName
        const res = await querySalesmanList({ orgSNNo: value.orgSNNo, currentPage: 1, pageSize: 999, utype: 8388608 })
        this.driverList = res.data.rows
      },
      selectClearable() {
        this.dataForm.newDriverCode = ''
        this.driverList = []
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'timeRange') {
                if (obj['timeRange'].length > 0) {
                  query['createTimeStart'] = parseTime(obj[key][0], '{y}-{m}-{d} {h}:{i}:{s}')
                  query['createTimeEnd'] = parseTime(obj[key][1], '{y}-{m}-{d} {h}:{i}:{s}')
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const res = await queryDriverPriceList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      search() {
        if (!this.qtype && this.query.param) {
          this.$message.warning('请选择查询条件')
          return
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打开详情
      async openDetail(row, type) {
        await this.$refs.cartDriverDetail.open(row, type)
      },
      // 新增报价
      async setPrice(row) {
        this.$refs.addQuotedPrice.open(row)
      },
      // 查看报价
      async detail(row) {
        this.$refs.addQuotedPrice.open(row, '查看')
      },
      // 取消
      async cancel(formName) {
        await this.reset()
        this.visible = false
      },
      // 更新表格
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') < parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')) {
          return 'danger-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    display: flex;
    width: 50%;
    padding-right: 10px;
    // .el-form-item__content {
    //   width: 100%;
    // }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}

</style>
